--[[ =========================================================================
   ROCKET AVIATOR -- jeu de crash en montgolfiere, pour CC:Tweaked
   -------------------------------------------------------------------------
   A installer sur un ADVANCED COMPUTER avec :
     - un GRAND MONITEUR AVANCE tactile (8x5 blocs conseille) : le vol
     - un petit moniteur optionnel (3x2) : les derniers vols et les records
     - un Wired Modem
     - client_solde.lua et login_term.lua sur le meme computer

   Tu t'inscris et tu mises sur le terminal, puis tout se joue sur le
   moniteur : la montgolfiere monte, le multiplicateur grimpe, et tu
   TOUCHES L'ECRAN pour encaisser avant qu'elle ne s'envole.

   MATHEMATIQUES
   La loi de crash est P(crash >= x) = RTP / x. Sa propriete remarquable :
   le RTP est le MEME quelle que soit la cible du joueur. Mesure sur
   3 millions de vols simules : encaisser a x1,2 rend 0,970, a x10 rend
   0,969, a x100 rend 0,969. Personne ne peut trouver de strategie
   gagnante, et personne n'est puni pour sa prudence.
========================================================================= ]]

--------------------------------------------------------------------------
-- CONFIGURATION
--------------------------------------------------------------------------
local CFG = {
  rtp         = 110,
  fps         = 15,
  growth      = 0.22,      -- vitesse de montee du multiplicateur
  betLevels   = { 10, 25, 50, 100, 250, 500, 1000 },
  autoTargets = { 0, 1.5, 2, 3, 5, 10 },   -- 0 = encaissement manuel
  countdown   = 3,
  resultTime  = 6,
  histFile    = "aviator_hist.dat",
  histMax     = 30,
  bigMonitor  = nil,       -- nil = detection automatique
  sideMonitor = nil,
}

--------------------------------------------------------------------------
-- PERIPHERIQUES
--------------------------------------------------------------------------
local bank  = dofile("client_solde.lua")
local login = dofile("login_term.lua")

local mon, monSide
if CFG.bigMonitor then mon = peripheral.wrap(CFG.bigMonitor) end
if CFG.sideMonitor then monSide = peripheral.wrap(CFG.sideMonitor) end
if not mon or not monSide then
  -- le plus grand ecran prend le vol, l'autre le tableau
  local found = { peripheral.find("monitor") }
  table.sort(found, function(a, b)
    local aw, ah = a.getSize()
    local bw, bh = b.getSize()
    return aw * ah > bw * bh
  end)
  if not mon then mon = found[1] end
  if not monSide then
    for _, m in ipairs(found) do
      if m ~= mon then monSide = m; break end
    end
  end
end
if not mon then error("Aucun moniteur trouve (il doit etre avance).", 0) end

local speaker = peripheral.find("speaker")
local function beep(p, inst)
  if speaker then pcall(speaker.playNote, inst or "bit", 1, p or 12) end
end

--------------------------------------------------------------------------
-- PALETTE
--------------------------------------------------------------------------
local PAL = {
  ["0"] = 0xffffff, ["1"] = 0xff7a18, ["2"] = 0x2fa3f0, ["3"] = 0xa8dcff,
  ["4"] = 0xffd23f, ["5"] = 0x9dff5c, ["6"] = 0xff5fb0, ["7"] = 0x0a0a18,
  ["8"] = 0x3c3c4a, ["9"] = 0x14406e, ["a"] = 0x8b5cd6, ["b"] = 0x1b2a5c,
  ["c"] = 0x7a0f16, ["d"] = 0x2fa84f, ["e"] = 0xd11f2a, ["f"] = 0x000000,
}

for _, m in ipairs({ mon, monSide }) do
  if m then
    m.setTextScale(0.5)
    for hex, rgb in pairs(PAL) do
      pcall(m.setPaletteColour, 2 ^ tonumber(hex, 16), rgb)
    end
  end
end

--------------------------------------------------------------------------
-- FABRIQUE D'ECRANS
--------------------------------------------------------------------------
local function makeScreen(m)
  local sc = { mon = m, sx = 0, sy = 0 }
  function sc.init()
    sc.W, sc.H = m.getSize()
    sc.t, sc.f, sc.b = {}, {}, {}
    for y = 1, sc.H do sc.t[y], sc.f[y], sc.b[y] = {}, {}, {} end
  end
  function sc.clear(bg)
    bg = bg or "f"
    for y = 1, sc.H do
      for x = 1, sc.W do sc.t[y][x], sc.f[y][x], sc.b[y][x] = " ", "f", bg end
    end
  end
  function sc.px(x, y, bg)
    x = math.floor(x + sc.sx); y = math.floor(y + sc.sy)
    if x >= 1 and x <= sc.W and y >= 1 and y <= sc.H then
      sc.t[y][x], sc.f[y][x], sc.b[y][x] = " ", "f", bg or "f"
    end
  end
  function sc.rect(x1, y1, x2, y2, bg)
    for y = math.floor(y1), math.floor(y2) do
      for x = math.floor(x1), math.floor(x2) do sc.px(x, y, bg) end
    end
  end
  function sc.text(x, y, s, fg, bg)
    x = math.floor(x + sc.sx); y = math.floor(y + sc.sy)
    for i = 1, #s do
      local xx = x + i - 1
      if xx >= 1 and xx <= sc.W and y >= 1 and y <= sc.H then
        sc.t[y][xx] = s:sub(i, i)
        sc.f[y][xx] = fg or "0"
        if bg then sc.b[y][xx] = bg end
      end
    end
  end
  function sc.center(x1, x2, y, s, fg, bg)
    sc.text(math.floor(x1 + ((x2 - x1 + 1) - #s) / 2), y, s, fg, bg)
  end
  function sc.push()
    for y = 1, sc.H do
      m.setCursorPos(1, y)
      m.blit(table.concat(sc.t[y]), table.concat(sc.f[y]), table.concat(sc.b[y]))
    end
  end
  sc.init()
  return sc
end

local S = makeScreen(mon)                       -- ecran principal
local T = monSide and makeScreen(monSide) or nil -- tableau lateral

--------------------------------------------------------------------------
-- FONTE 5x7
--------------------------------------------------------------------------
local FONT = {
  R="11110/10001/10001/11110/10100/10010/10001",
  O="01110/10001/10001/10001/10001/10001/01110",
  C="01110/10001/10000/10000/10000/10001/01110",
  K="10001/10010/10100/11000/10100/10010/10001",
  E="11111/10000/10000/11110/10000/10000/11111",
  T="11111/00100/00100/00100/00100/00100/00100",
  A="01110/10001/10001/11111/10001/10001/10001",
  V="10001/10001/10001/10001/10001/01010/00100",
  I="11111/00100/00100/00100/00100/00100/11111",
  N="10001/11001/10101/10011/10001/10001/10001",
  S="01111/10000/10000/01110/00001/00001/11110",
  L="10000/10000/10000/10000/10000/10000/11111",
  D="11110/10001/10001/10001/10001/10001/11110",
  G="01110/10001/10000/10111/10001/10001/01111",
  U="10001/10001/10001/10001/10001/10001/01110",
  P="11110/10001/10001/11110/10000/10000/10000",
  M="10001/11011/10101/10101/10001/10001/10001",
  X="10001/10001/01010/00100/01010/10001/10001",
  ["!"]="00100/00100/00100/00100/00100/00000/00100",
  ["."]="00000/00000/00000/00000/00000/01100/01100",
  ["0"]="01110/10011/10101/10101/11001/10001/01110",
  ["1"]="00100/01100/00100/00100/00100/00100/01110",
  ["2"]="01110/10001/00001/00110/01000/10000/11111",
  ["3"]="11111/00010/00100/00010/00001/10001/01110",
  ["4"]="00010/00110/01010/10010/11111/00010/00010",
  ["5"]="11111/10000/11110/00001/00001/10001/01110",
  ["6"]="00110/01000/10000/11110/10001/10001/01110",
  ["7"]="11111/00001/00010/00100/01000/01000/01000",
  ["8"]="01110/10001/10001/01110/10001/10001/01110",
  ["9"]="01110/10001/10001/01111/00001/00010/01100",
  [" "]="00000/00000/00000/00000/00000/00000/00000",
}
local GLYPH = {}
for ch, def in pairs(FONT) do
  local rows = {}
  for r in def:gmatch("[^/]+") do rows[#rows + 1] = r end
  GLYPH[ch] = rows
end

local function bigWidth(s, sx) sx = sx or 1; return #s * (5 * sx + sx) - sx end

local function bigText(sc, x0, y0, s, colFn, sx, sy)
  sx, sy = sx or 1, sy or 1
  local cx = x0
  for i = 1, #s do
    local g = GLYPH[s:sub(i, i)] or GLYPH[" "]
    for ry = 1, 7 do
      for rx = 1, 5 do
        if g[ry]:sub(rx, rx) == "1" then
          for iy = 0, sy - 1 do
            for ix = 0, sx - 1 do
              sc.px(cx + (rx - 1) * sx + ix, y0 + (ry - 1) * sy + iy,
                    colFn(cx + (rx - 1) * sx + ix, ry))
            end
          end
        end
      end
    end
    cx = cx + 5 * sx + sx
  end
end

--------------------------------------------------------------------------
-- LA MONTGOLFIERE MIAOUSS
--------------------------------------------------------------------------
-- Dessinee proportionnellement : la meme fonction sert pour la petite
-- montgolfiere en vol et pour l'enorme de l'ecran de veille.
local function drawBalloon(sc, cx, cy, rx, ry, t, face)
  -- oreilles de Miaouss : posees sur la surface de l'enveloppe, pas
  -- flottant au-dessus. On calcule la hauteur de l'ellipse a leur
  -- abscisse pour qu'elles s'y raccordent exactement.
  local exr = 0.44
  local ex = math.max(1, math.floor(rx * exr))
  local eh = math.max(2, math.floor(ry * 0.42))
  local base = math.floor(cy - ry * math.sqrt(1 - exr * exr)) + 1
  for k = 0, eh do
    local w = math.max(0, math.floor((eh - k) * 0.85))
    for side = -1, 1, 2 do
      for dx = -w, w do
        local xx = cx + side * ex + dx
        local yy = base - eh + k
        sc.px(xx, yy, (math.abs(dx) == w or k == 0) and "f" or "4")
      end
    end
  end

  -- enveloppe : fuseaux rouges et blancs
  for y = math.floor(cy - ry), math.floor(cy + ry) do
    for x = math.floor(cx - rx), math.floor(cx + rx) do
      local nx, ny = (x - cx) / rx, (y - cy) / ry
      local d = nx * nx + ny * ny
      if d <= 1 then
        local band = math.floor(((x - cx) / rx + 1) * 3.5)
        local col = (band % 2 == 0) and "4" or "0"
        if d > 0.88 then col = "f" end
        sc.px(x, y, col)
      end
    end
  end

  if face then
    -- visage de Miaouss sur l'enveloppe
    local fy = math.floor(cy - ry * 0.15)
    local eyw = math.max(1, math.floor(rx * 0.10))
    for side = -1, 1, 2 do
      local exx = cx + side * math.floor(rx * 0.34)
      sc.rect(exx - eyw, fy - 1, exx + eyw, fy + 1, "f")
    end
    -- la piece d'or sur le front
    local cy2 = math.floor(cy - ry * 0.55)
    local cw = math.max(1, math.floor(rx * 0.16))
    sc.rect(cx - cw, cy2 - 1, cx + cw, cy2 + 1, "1")
    sc.rect(cx - cw + 1, cy2, cx + cw - 1, cy2, "4")
    -- museau et moustaches
    local my = math.floor(cy + ry * 0.18)
    sc.rect(cx - 1, my, cx + 1, my, "e")
    for side = -1, 1, 2 do
      for k = 1, math.max(2, math.floor(rx * 0.30)) do
        sc.px(cx + side * (3 + k), my - 1, "f")
        sc.px(cx + side * (3 + k), my + 1, "f")
      end
    end
  end

  -- cordages et nacelle
  local by = math.floor(cy + ry + math.max(2, ry * 0.30))
  local bw = math.max(2, math.floor(rx * 0.34))
  for side = -1, 1, 2 do
    local x0 = cx + side * math.floor(rx * 0.62)
    local x1 = cx + side * bw
    local steps = by - (cy + ry)
    for k = 0, steps do
      local u = (steps == 0) and 0 or k / steps
      sc.px(x0 + (x1 - x0) * u, cy + ry + k, "8")
    end
  end
  sc.rect(cx - bw, by, cx + bw, by + math.max(1, math.floor(ry * 0.22)), "c")
  sc.center(cx - bw, cx + bw, by, "R", "4", "c")

  -- flamme du bruleur, elle vacille
  if math.floor(t * 8) % 2 == 0 then
    sc.px(cx, cy + ry + 1, "1")
    sc.px(cx, cy + ry + 2, "4")
  end
end

--------------------------------------------------------------------------
-- HISTORIQUE PERSISTANT
--------------------------------------------------------------------------
local function loadHist()
  if not fs.exists(CFG.histFile) then return { flights = {}, best = 0,
                                               bestPlayer = "-", bestWin = 0,
                                               bestWinPlayer = "-" } end
  local f = fs.open(CFG.histFile, "r")
  local d = textutils.unserialize(f.readAll() or "")
  f.close()
  if type(d) ~= "table" then
    return { flights = {}, best = 0, bestPlayer = "-", bestWin = 0,
             bestWinPlayer = "-" }
  end
  d.flights = d.flights or {}
  return d
end

local function saveHist(h)
  local f = fs.open(CFG.histFile, "w")
  f.write(textutils.serialize(h))
  f.close()
end

local HIST = loadHist()

local function recordFlight(crash, player, win)
  table.insert(HIST.flights, crash)
  while #HIST.flights > CFG.histMax do table.remove(HIST.flights, 1) end
  if crash > (HIST.best or 0) then
    HIST.best = crash
    HIST.bestPlayer = player or "-"
  end
  if (win or 0) > (HIST.bestWin or 0) then
    HIST.bestWin = win
    HIST.bestWinPlayer = player or "-"
  end
  saveHist(HIST)
end

--------------------------------------------------------------------------
-- OUTILS
--------------------------------------------------------------------------
local function fmt(n)
  local s = tostring(math.floor(n))
  local out = ""
  while #s > 3 do out = " " .. s:sub(-3) .. out; s = s:sub(1, -4) end
  return s .. out
end

local function mult(x) return string.format("%.2f", x) end

local function multColor(x)
  if x >= 10 then return "4" end
  if x >= 5 then return "1" end
  if x >= 2 then return "a" end
  return "2"
end

-- tirage du point de crash : P(crash >= x) = RTP / x
local function drawCrash()
  local u = math.random()
  if u <= 0 then return 1.00 end
  local x = CFG.rtp / u
  if x < 1 then return 1.00 end
  return math.floor(x * 100) / 100
end

--------------------------------------------------------------------------
-- MISE EN PAGE DE L'ECRAN PRINCIPAL
--------------------------------------------------------------------------
local L = {}
local function layout()
  S.init()
  L.x1, L.y1, L.x2, L.y2 = 2, 2, S.W - 1, S.H - 1
  L.histY = L.y2
  L.skyY2 = L.histY - 2
  L.groundY = L.skyY2
end
layout()

local CHASE = { "4", "1", "e", "c" }
local function drawFrame(sc, t, flash)
  local step = math.floor(t * 6)
  for x = 1, sc.W do
    local a = flash and (((x + step * 2) % 4 < 2) and "0" or "4")
              or CHASE[((x + step) % 4) + 1]
    sc.px(x, 1, a); sc.px(x, sc.H, a)
  end
  for y = 1, sc.H do
    local a = flash and (((y + step * 2) % 4 < 2) and "0" or "4")
              or CHASE[((y + step) % 4) + 1]
    sc.px(1, y, a); sc.px(sc.W, y, a)
  end
end

-- ciel : bleu au sol, nuit etoilee en altitude
local function drawSky(alt, t)
  local top, bot = L.y1, L.skyY2
  for y = top, bot do
    local h = (bot - y) / math.max(1, bot - top)      -- 0 en bas, 1 en haut
    local a = math.min(1, alt + h * 0.55)
    local col
    if a < 0.30 then col = "3"
    elseif a < 0.55 then col = "2"
    elseif a < 0.80 then col = "9"
    elseif a < 1.05 then col = "b"
    else col = "7" end
    for x = L.x1, L.x2 do S.px(x, y, col) end
  end
  -- etoiles quand on monte
  if alt > 0.45 then
    local n = math.floor((alt - 0.45) * 90)
    for i = 1, math.min(n, 70) do
      local sx = L.x1 + ((i * 37 + 11) % (L.x2 - L.x1))
      local sy = top + ((i * 17) % math.max(1, math.floor((bot - top) * 0.7)))
      if math.floor(t * 3 + i) % 5 ~= 0 then S.px(sx, sy, "0") end
    end
  end
  -- nuages qui defilent vers le bas
  for i = 1, 6 do
    local cy = bot - ((i * 13 + math.floor(alt * 120 + t * 6)) %
               math.max(1, bot - top + 10)) + 5
    local cx = L.x1 + ((i * 29 + 7) % (L.x2 - L.x1 - 10))
    if cy >= top and cy <= bot then
      S.rect(cx, cy, cx + 7, cy, "0")
      S.rect(cx + 2, cy - 1, cx + 5, cy - 1, "0")
    end
  end
end

local function drawHistoryStrip()
  local y = L.histY
  S.rect(L.x1, y - 1, L.x2, y, "f")
  local s = "DERNIERS VOLS : "
  S.text(L.x1, y, s, "8")
  local x = L.x1 + #s
  for i = #HIST.flights, 1, -1 do
    local v = HIST.flights[i]
    local lbl = "x" .. mult(v)
    if x + #lbl + 1 > L.x2 then break end
    S.text(x, y, lbl, multColor(v))
    x = x + #lbl + 1
  end
end

--------------------------------------------------------------------------
-- TABLEAU LATERAL (moniteur optionnel)
--------------------------------------------------------------------------
local function drawSide(t, state, cur)
  if not T then return end
  T.clear("f")
  T.rect(1, 1, T.W, 1, "e")
  T.center(1, T.W, 1, "ROCKET AVIATOR", "4", "e")

  local y = 3
  T.text(2, y, "DERNIERS VOLS", "8")
  y = y + 1
  local x = 2
  for i = #HIST.flights, 1, -1 do
    local v = HIST.flights[i]
    local lbl = "x" .. mult(v)
    if x + #lbl + 1 > T.W - 1 then
      x = 2; y = y + 1
      if y > T.H - 6 then break end
    end
    T.text(x, y, lbl, multColor(v))
    x = x + #lbl + 1
  end

  local by = T.H - 4
  T.rect(1, by - 1, T.W, by - 1, "8")
  T.text(2, by, "RECORD  x" .. mult(HIST.best or 0), "4")
  T.text(2, by + 1, "par " .. tostring(HIST.bestPlayer), "3")
  T.text(2, by + 2, "GROS GAIN  " .. fmt(HIST.bestWin or 0), "5")
  T.text(2, by + 3, "par " .. tostring(HIST.bestWinPlayer), "3")

  if state == "vol" and cur then
    T.rect(1, 2, T.W, 2, "d")
    T.center(1, T.W, 2, "EN VOL  x" .. mult(cur), "f", "d")
  end
  T.push()
end

--------------------------------------------------------------------------
-- ETAT PARTAGE
--------------------------------------------------------------------------
local STATE = { playing = false }

--------------------------------------------------------------------------
-- ECRAN DE VEILLE : l'enorme montgolfiere, facon enseigne
--------------------------------------------------------------------------
local TAUNTS = {
  "Jusqu'ou oseras-tu monter ?",
  "La Team Rocket ne rembourse pas les etourdis.",
  "Encaisse trop tot, tu regretteras.",
  "Encaisse trop tard, tu regretteras aussi.",
  "Miaouss surveille l'altimetre.",
}

local function attractFrame(t)
  S.clear("f")

  -- ciel de nuit avec etoiles fixes qui scintillent
  for y = L.y1, L.skyY2 do
    local h = (L.skyY2 - y) / math.max(1, L.skyY2 - L.y1)
    local col = (h > 0.62) and "7" or ((h > 0.34) and "b" or "9")
    for x = L.x1, L.x2 do S.px(x, y, col) end
  end
  for i = 1, 60 do
    local sx = L.x1 + ((i * 41 + 5) % (L.x2 - L.x1))
    local sy = L.y1 + ((i * 23) % math.max(1, math.floor((L.skyY2 - L.y1) * 0.8)))
    if math.floor(t * 2 + i) % 4 ~= 0 then S.px(sx, sy, "0") end
  end

  -- l'enorme montgolfiere, a droite, qui flotte doucement
  local ry = math.max(6, math.floor((L.skyY2 - L.y1) * 0.34))
  local rx = math.floor(ry * 1.6)
  local bx = L.x2 - rx - 4
  local by = L.y1 + ry + math.max(4, math.floor(ry * 0.45))
             + math.floor(math.sin(t * 0.8) * 1.5)
  drawBalloon(S, bx, by, rx, ry, t, true)

  -- titre, dans le style de l'enseigne : degrade or et reflet qui balaye
  local title = "ROCKET"
  local title2 = "AVIATOR"
  local avail = bx - rx - L.x1 - 4
  local sc = 1
  if bigWidth(title2, 2) <= avail then sc = 2 end
  local sweep = (t * 26) % 140 - 30
  local function col(x, gy)
    local d = x - L.x1 - sweep
    if d > -2 and d < 2 then return "0" end
    if gy <= 3 then return "4" elseif gy <= 5 then return "1" else return "e" end
  end
  local ty = L.y1 + math.max(2, math.floor((L.skyY2 - L.y1) / 2) - 8)
  bigText(S, L.x1 + 3, ty + 1, title, function() return "f" end, sc, sc)
  bigText(S, L.x1 + 2, ty, title, col, sc, sc)
  bigText(S, L.x1 + 3, ty + 8 * sc + 1, title2, function() return "f" end, sc, sc)
  bigText(S, L.x1 + 2, ty + 8 * sc, title2, col, sc, sc)

  S.text(L.x1 + 2, ty + 16 * sc + 1, "TEAM ROCKET AIRLINES", "6")
  S.center(L.x1, L.x2, L.skyY2 - 2,
           "INSCRIS-TOI SUR LE TERMINAL POUR DECOLLER", "0")
  S.center(L.x1, L.x2, L.skyY2 - 1,
           TAUNTS[(math.floor(t / 5) % #TAUNTS) + 1], "3")

  drawHistoryStrip()
  drawFrame(S, t)
  S.push()
  drawSide(t, "veille")
end

local function attractLoop()
  while true do
    if not STATE.playing then pcall(attractFrame, os.clock()) end
    sleep(1 / 8)
  end
end

--------------------------------------------------------------------------
-- LE VOL
--------------------------------------------------------------------------
local function runFlight(player, bet, autoTarget)
  STATE.playing = true
  local crash = drawCrash()
  local t0 = os.clock()

  -- compte a rebours
  for i = CFG.countdown, 1, -1 do
    S.clear("f")
    drawSky(0, os.clock())
    local s = tostring(i)
    local w = bigWidth(s, 4)
    bigText(S, math.floor((S.W - w) / 2), math.floor(S.H / 2) - 14, s,
            function() return "4" end, 4, 4)
    S.center(L.x1, L.x2, math.floor(S.H / 2) + 16, "PREPAREZ-VOUS", "0")
    S.center(L.x1, L.x2, math.floor(S.H / 2) + 18,
             "TOUCHE L'ECRAN POUR ENCAISSER", "6")
    drawHistoryStrip()
    drawFrame(S, os.clock())
    S.push()
    beep(8 + i * 2)
    sleep(0.8)
  end

  local start = os.clock()
  local cur, cashed = 1.00, nil
  local curve = {}
  local timer = os.startTimer(1 / CFG.fps)
  local crashed = false
  local endAt = nil

  while true do
    local ev, p1, p2, p3 = os.pullEvent()
    local now = os.clock()

    if ev == "monitor_touch" and not cashed and not crashed then
      cashed = cur
      beep(20, "bell")

    elseif ev == "timer" and p1 == timer then
      timer = os.startTimer(1 / CFG.fps)
      local el = now - start

      if not crashed then
        cur = math.exp(CFG.growth * el)
        cur = math.floor(cur * 100) / 100
        if not cashed and autoTarget > 0 and cur >= autoTarget then
          cashed = math.min(cur, autoTarget)
          beep(20, "bell")
        end
        if cur >= crash then
          cur = crash
          crashed = true
          endAt = now + CFG.resultTime
          beep(3, "bass")
        end
        if cashed and not endAt then
          endAt = now + CFG.resultTime
          crashed = false
        end
      end

      -- altitude normalisee, pour le ciel et la courbe
      local alt = math.min(1.25, math.log(math.max(1, cur)) / 3.2)

      S.clear("f")
      drawSky(alt, now)

      -- courbe de vol
      local gx1, gx2 = L.x1 + 2, L.x2 - 2
      local gy1, gy2 = L.y1 + 4, L.skyY2 - 2
      curve[#curve + 1] = cur
      while #curve > (gx2 - gx1) do table.remove(curve, 1) end
      local lastX, lastY
      for i, v in ipairs(curve) do
        local x = gx1 + i - 1
        local a = math.min(1, math.log(math.max(1, v)) / 3.2)
        local y = gy2 - a * (gy2 - gy1)
        S.px(x, y, crashed and "e" or "4")
        if lastY then
          for yy = math.min(y, lastY), math.max(y, lastY) do
            S.px(x, yy, crashed and "e" or "4")
          end
        end
        lastX, lastY = x, y
      end

      -- la montgolfiere en tete de courbe
      if lastX and not crashed then
        local ry = math.max(3, math.floor(S.H * 0.08))
        local rx = math.floor(ry * 1.6)
        drawBalloon(S, math.min(lastX, gx2 - rx - 1),
                    math.max(gy1 + ry + 2, lastY - ry - 3), rx, ry, now, true)
      elseif crashed and lastX then
        -- elle s'envole vers les etoiles
        local age = now - (endAt - CFG.resultTime)
        local ry = math.max(2, math.floor(S.H * 0.06))
        local rx = math.floor(ry * 1.6)
        drawBalloon(S, lastX + age * 6, lastY - age * 14, rx, ry, now, false)
        for k = 1, 20 do
          local ang = k * math.pi / 10
          local r = age * 18
          S.px(lastX + math.cos(ang) * r * 1.6, lastY + math.sin(ang) * r,
               (k % 2 == 0) and "1" or "e")
        end
      end

      -- multiplicateur geant
      local s = "X" .. mult(cur)
      local msc = (S.W >= 90) and 3 or 2
      local w = bigWidth(s, msc)
      local mx = math.floor((S.W - w) / 2)
      local my = L.y1 + 3
      bigText(S, mx + 1, my + 1, s, function() return "f" end, msc, msc)
      bigText(S, mx, my, s, function(_, gy)
        if crashed then return (math.floor(now * 8) % 2 == 0) and "0" or "e" end
        if cashed then return "5" end
        return gy <= 3 and "4" or "1"
      end, msc, msc)

      -- bandeau d'etat
      local info
      if crashed then info = "ENVOLEE ! Le vol s'arrete a x" .. mult(crash)
      elseif cashed then info = "ENCAISSE x" .. mult(cashed) ..
                                "  ->  " .. fmt(bet * cashed) .. " credits"
      else info = "TOUCHE L'ECRAN POUR ENCAISSER   mise " .. fmt(bet) ..
                  "   gain actuel " .. fmt(bet * cur) end
      S.rect(L.x1, L.skyY2 - 1, L.x2, L.skyY2 - 1,
             crashed and "e" or (cashed and "d" or "f"))
      S.center(L.x1, L.x2, L.skyY2 - 1, info,
               (crashed or cashed) and "0" or "4",
               crashed and "e" or (cashed and "d" or "f"))
      if autoTarget > 0 and not cashed and not crashed then
        S.text(L.x1, L.y1 + 1, "AUTO x" .. mult(autoTarget), "6")
      end
      S.text(L.x1, L.y1, player, "3")

      drawHistoryStrip()
      drawFrame(S, now, crashed or (cashed ~= nil))
      S.push()
      drawSide(now, "vol", cur)

      if endAt and now >= endAt then break end
    end
  end

  STATE.playing = false
  local win = cashed and math.floor(bet * cashed) or 0
  recordFlight(crash, player, win)
  return crash, cashed, win
end

--------------------------------------------------------------------------
-- TERMINAL
--------------------------------------------------------------------------
local TW, TH = term.getSize()

local function tFill(y, bg)
  term.setBackgroundColor(bg)
  term.setCursorPos(1, y)
  term.write(string.rep(" ", TW))
end

local function tLabel(x, y, s, fg, bg)
  term.setCursorPos(x, y)
  term.setTextColor(fg)
  term.setBackgroundColor(bg or colors.black)
  term.write(s)
end

local function tCenter(y, s, fg, bg)
  tLabel(math.floor((TW - #s) / 2) + 1, y, s, fg, bg)
end

local function splash()
  term.setBackgroundColor(colors.black)
  term.clear()
  tFill(1, colors.red)
  tCenter(1, "ROCKET AVIATOR", colors.yellow, colors.red)
  tCenter(3, "Team Rocket Airlines", colors.lightGray)
  tCenter(5, "La montgolfiere monte, le multiplicateur grimpe.", colors.white)
  tCenter(6, "Touche le moniteur pour encaisser avant l'envolee.", colors.white)
  tCenter(8, "Record : x" .. mult(HIST.best or 0) ..
          " par " .. tostring(HIST.bestPlayer), colors.yellow)
  tCenter(TH - 2, "Une touche pour embarquer", colors.yellow)
  while true do
    local ev = os.pullEvent()
    if ev == "key" or ev == "mouse_click" then return end
  end
end

local function lobby(player)
  local betIdx, autoIdx = 3, 1
  local credit = bank.getBalance(player)
  local buttons

  local function draw(msg, col)
    buttons = {}
    term.setBackgroundColor(colors.black)
    term.clear()
    tFill(1, colors.red)
    tLabel(2, 1, "ROCKET AVIATOR", colors.yellow, colors.red)
    local right = player .. "  " .. fmt(credit)
    tLabel(TW - #right, 1, right, colors.white, colors.red)

    tLabel(2, 3, "MISE", colors.lightGray)
    term.setBackgroundColor(colors.red)
    term.setCursorPos(8, 3); term.write(" - ")
    buttons[#buttons + 1] = { id = "bet-", x1 = 8, x2 = 10, y = 3 }
    term.setBackgroundColor(colors.green)
    term.setCursorPos(20, 3); term.write(" + ")
    buttons[#buttons + 1] = { id = "bet+", x1 = 20, x2 = 22, y = 3 }
    tLabel(13, 3, fmt(CFG.betLevels[betIdx]), colors.yellow)

    tLabel(2, 5, "AUTO", colors.lightGray)
    term.setBackgroundColor(colors.red)
    term.setCursorPos(8, 5); term.write(" - ")
    buttons[#buttons + 1] = { id = "auto-", x1 = 8, x2 = 10, y = 5 }
    term.setBackgroundColor(colors.green)
    term.setCursorPos(20, 5); term.write(" + ")
    buttons[#buttons + 1] = { id = "auto+", x1 = 20, x2 = 22, y = 5 }
    local a = CFG.autoTargets[autoIdx]
    tLabel(12, 5, (a == 0) and "manuel" or ("x" .. mult(a)), colors.yellow)

    tLabel(2, 7, (a == 0) and "Tu encaisses en touchant le moniteur"
           or "Encaissement automatique a x" .. mult(a), colors.lightGray)

    term.setBackgroundColor(colors.green)
    term.setCursorPos(2, 9); term.write(string.rep(" ", 22))
    tLabel(6, 9, "DECOLLAGE", colors.white, colors.green)
    buttons[#buttons + 1] = { id = "go", x1 = 2, x2 = 23, y = 9 }

    term.setBackgroundColor(colors.red)
    term.setCursorPos(TW - 11, 9); term.write(string.rep(" ", 10))
    tLabel(TW - 9, 9, "QUITTER", colors.white, colors.red)
    buttons[#buttons + 1] = { id = "quit", x1 = TW - 11, x2 = TW - 2, y = 9 }

    tCenter(11, "Tout se joue sur le moniteur", colors.lightGray)
    tFill(TH, colors.gray)
    if msg then tCenter(TH, msg, col or colors.white, colors.gray) end
  end

  draw("Espace = decollage, +/- = mise")
  while true do
    local ev, p1, p2, p3 = os.pullEvent()
    local action
    if ev == "mouse_click" then
      for _, b in ipairs(buttons) do
        if p3 == b.y and p2 >= b.x1 and p2 <= b.x2 then action = b.id end
      end
    elseif ev == "key" then
      if p1 == keys.q then action = "quit"
      elseif p1 == keys.space or p1 == keys.enter then action = "go"
      elseif p1 == keys.equals or p1 == keys.numPadAdd then action = "bet+"
      elseif p1 == keys.minus or p1 == keys.numPadSubtract then action = "bet-"
      elseif p1 == keys.up then action = "auto+"
      elseif p1 == keys.down then action = "auto-"
      end
    end

    if action == "quit" then return
    elseif action == "bet+" then
      betIdx = math.min(betIdx + 1, #CFG.betLevels); draw()
    elseif action == "bet-" then
      betIdx = math.max(betIdx - 1, 1); draw()
    elseif action == "auto+" then
      autoIdx = math.min(autoIdx + 1, #CFG.autoTargets); draw()
    elseif action == "auto-" then
      autoIdx = math.max(autoIdx - 1, 1); draw()
    elseif action == "go" then
      local bet = CFG.betLevels[betIdx]
      local newBal, err = bank.addBalance(player, -bet)
      if not newBal then
        draw(err or "Banque injoignable", colors.red)
      else
        credit = newBal
        term.setBackgroundColor(colors.black)
        term.clear()
        tCenter(math.floor(TH / 2) - 1, "REGARDE LE MONITEUR", colors.yellow)
        tCenter(math.floor(TH / 2) + 1,
                "Touche l'ecran pour encaisser", colors.white)
        local crash, cashed, win =
          runFlight(player, bet, CFG.autoTargets[autoIdx])
        if win > 0 then
          local nb = bank.addBalance(player, win)
          credit = nb or (credit + win)
        end
        if cashed then
          draw("Encaisse a x" .. mult(cashed) .. "  ->  +" .. fmt(win) ..
               "   (envolee a x" .. mult(crash) .. ")", colors.lime)
        else
          draw("Envolee a x" .. mult(crash) .. "  -  mise perdue", colors.red)
        end
      end
    end
  end
end

--------------------------------------------------------------------------
-- PROGRAMME PRINCIPAL
--------------------------------------------------------------------------
math.randomseed((os.epoch and os.epoch("utc") or os.time()) % 2147483647)

print("=== Rocket Aviator ===")
print("Vol    : " .. peripheral.getName(mon) .. "  " .. S.W .. "x" .. S.H)
if T then
  print("Tableau: " .. peripheral.getName(monSide) .. "  " .. T.W .. "x" .. T.H)
else
  print("Tableau: aucun second moniteur (optionnel)")
end
print(string.format("RTP %.0f %%, identique quelle que soit la strategie",
      CFG.rtp * 100))

local function mainLoop()
  while true do
    splash()
    local player = login.authenticate("Connexion Rocket Aviator")
    if player then lobby(player) end
  end
end

local ok, err = pcall(function()
  parallel.waitForAny(mainLoop, attractLoop)
end)

term.setBackgroundColor(colors.black)
term.setTextColor(colors.white)
term.clear()
term.setCursorPos(1, 1)
mon.setBackgroundColour(colours.black)
mon.clear()
if monSide then monSide.setBackgroundColour(colours.black); monSide.clear() end
if not ok and err ~= "Terminated" then error(err, 0) end
print("Rocket Aviator : arret.")
